//
//  Common.m
//  供销宝
//
//  Created by 金晶 on 17/2/6.
//  Copyright © 2017年 金晶. All rights reserved.
//

#import "Common.h"

// 1s  length 75
// 60s  6~197 6p~230
#define MAX_IMAGE_WH 141.0


static Common *manager = nil;

@implementation Common


+ (Common *)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        manager = [[super allocWithZone:NULL] init];
    });
    return manager;
}

+ (instancetype)allocWithZone:(NSZone *)zone {
    
    return [self manager];
}

/*密码验证 8位以上，英文+字母*/
- (BOOL)isValidatePassWord:(NSString *)password {
    
    NSString *passRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
    
    NSPredicate *passText = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passRegex];
    
    return [passText evaluateWithObject:password];
}

/*手机号码验证*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

//身份证号
- (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

/*邮箱验证 */
-(BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/*! 倒计时方法*/
-(void)getfirstActivityCountWithtime:(int)time WithButton:(UIButton *)button forEnd:(void (^)(void))end{
    
    [self getActivityCountdownforTime:time WithButton:button forEnd:end];
}

/*! 倒计时方法*  要写方法去掉用该方法*  入参时间与block*  block返回*/
-(void)getActivityCountdownforTime:(int)time WithButton:(UIButton *)button forEnd:(void (^)(void))end{
    
    __block int timeout = time;
    
    button.enabled = NO;
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1 * NSEC_PER_SEC,0);
    dispatch_source_set_event_handler(timer, ^{
        
        if(timeout<=0){
            dispatch_source_cancel(timer);
            //刷新主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                if(end){
                    end();
                }
            });
        }else{
            NSString *strTime = [self returnTime:timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //投置按钮
                [button setTitle:strTime forState:UIControlStateNormal];
                if(self.activityfail){
                    self.activityfail();
                }
            });
            timeout--;
        }
    });
    
    dispatch_resume(timer);
}

/*判断时间，可能是60s倒时计。
 * 也有可能是几天倒计时
 */
-(NSString *)returnTime:(int)time{
    
    if(time>60){
        int minutes = time /60;
        int seconds = time %60;
        
        return [NSString stringWithFormat:@"%d分.%.2d秒后重新获取验证码",minutes,seconds];
    }else{
        
        int seconds = time %60;
        
        if(seconds ==0){
            seconds = 60;
        }
        return [NSString stringWithFormat:@"%ds",seconds];
    }
}


/*计算文本的宽和高
 * 入参：字符串以为所适位于控制的高度
 * 返回为Size
 */
- (CGSize)calculationfontwidth:(NSString *)str Withheight:(CGFloat)height{
    
    CGSize size;
    
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:12]};
    
    size = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    
    return size;
}

/*判断图片长度&宽度*/
+ (CGSize)imageShowSize:(UIImage *)image{
    
    CGFloat imageWith=image.size.width;
    CGFloat imageHeight=image.size.height;
    
    //宽度大于高度
    if (imageWith>=imageHeight) {
        
        if(imageHeight==0) {
            return CGSizeMake(MAX_IMAGE_WH, 60);
        }else {
            return CGSizeMake(MAX_IMAGE_WH, imageHeight*MAX_IMAGE_WH/imageWith);
        }
        
    }else{
        
        return CGSizeMake(imageWith*MAX_IMAGE_WH/imageHeight, MAX_IMAGE_WH);
    }
    
    return CGSizeZero;
}

- (BOOL)decimalRestrictiontextField:(UITextField *)textField ChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 当前输入的字符是'.'
    if ([string isEqualToString:@"."]) {
        
        // 已输入的字符串中已经包含了'.'或者""
        if ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""]) {
            return NO;
        } else {
            return YES;
        }
    } else {// 当前输入的不是'.'
        // 第一个字符是0时, 第二个不能再输入0
        if (textField.text.length == 1) {
            unichar str = [textField.text characterAtIndex:0];
            if (str == '0' && [string isEqualToString:@"0"]) {
                return NO;
            }
            if (str != '0' && str != '1') {// 1xx或0xx
                return YES;
            } else {
                if (str == '1') {
                    return YES;
                } else {
                    if ([string isEqualToString:@""]) {
                        
                        return YES;
                    } else {
                        
                        return NO;
                    }
                }
            }
        }
        
        // 已输入的字符串中包含'.'
        if ([textField.text rangeOfString:@"."].location != NSNotFound) {
            
            NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
            [str insertString:string atIndex:range.location];
            
            if (str.length >= [str rangeOfString:@"."].location + 4) {
                
                return NO;
            }
            
        } else {
            
            if (textField.text.length > 5) {
                return range.location < 6;
            }
        }
    }
    return YES;
}

- (NSDictionary *)returnJsonData:(NSDictionary *)dict {
    
    NSString *str = [self returnJsonStr:dict];
    return @{@"jsonValue":str};
}

- (NSString *)returnJsonStr:(NSDictionary *)dict {
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}

- (NSString *)getCurrentTime:(DataType)type {
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    if(type ==DataTypehhmm) {
        [formatter setDateFormat:@"hh:mm"];
    }else if (type ==DataTypeyydd) {
        [formatter setDateFormat:@"yy:dd"];
    }else {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    
    NSString *DateTime = [formatter stringFromDate:date];
    
    return DateTime;
}

//计算文字宽度
- (CGRect)getContentWidth:(CGFloat)maxWith withcontent:(NSString *)str {
    
    CGRect rect;
    
    UIFont *textFont=[UIFont systemFontOfSize:15];
    
    NSDictionary *attributes = @{NSFontAttributeName: textFont};
    
    rect = [str boundingRectWithSize:CGSizeMake(maxWith, MAXFLOAT)
                             options:NSStringDrawingUsesLineFragmentOrigin
                          attributes:attributes
                             context:nil];
    return rect;
}

//随机生成msdid
- (NSString *)generateMsgId
{
    static int kNumber = 20;
    
    NSString *sourceStr = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    [resultStr appendString:[self timeInterval]];
    return resultStr;
}

- (NSString *)replaceEmoji:(NSString *)message {
    
    NSMutableAttributedString *aAttributedString = [[NSMutableAttributedString alloc]initWithString:message];
    NSString *rangeString = message;
    NSString *pattern = @"\\[[_\\[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]]";
    //创建匹配对象
    NSError *error;
    
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *resultArray = [regularExpression matchesInString:aAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, aAttributedString.string.length)];
    
    //开始遍历标题中所含的表情
    for (NSInteger i = resultArray.count - 1; i >= 0; i --)
    {
        //获取检查结果，里面有range
        NSTextCheckingResult * result = resultArray[i];
        //根据range获取字符串
        NSString *string = [aAttributedString.string substringWithRange:result.range];
        //获取图片
        
        rangeString = [rangeString stringByReplacingOccurrencesOfString:string withString:@"##"];
    }
    
    return rangeString;
}


- (NSMutableAttributedString *)facepattern:(NSString *)message {
    
    NSMutableAttributedString *aAttributedString = [[NSMutableAttributedString alloc]initWithString:message];
    
    NSString *pattern = @"\\[[_\\[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]]";
    //创建匹配对象
    NSError *error;
    
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *resultArray = [regularExpression matchesInString:aAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, aAttributedString.string.length)];
    
    //开始遍历标题中所含的表情
    for (NSInteger i = resultArray.count - 1; i >= 0; i --)
    {
        //获取检查结果，里面有range
        NSTextCheckingResult * result = resultArray[i];
        //根据range获取字符串
        NSString * rangeString = [aAttributedString.string substringWithRange:result.range];
        //获取图片
        UIImage * image = [self getImageWithRangeString:rangeString];//这是个自定义的方法
        
        if (image != nil)
        {
            //创建附件对象
            NSTextAttachment * imageTextAttachment = [[NSTextAttachment alloc]init];
            //设置图片属性
            imageTextAttachment.image = image;
            imageTextAttachment.bounds = CGRectMake(0, -5, 20, 20);
            //根据图片创建属性字符串
            NSAttributedString * imageAttributeString = [NSAttributedString attributedStringWithAttachment:imageTextAttachment];
            //开始替换
            [aAttributedString replaceCharactersInRange:result.range withAttributedString:imageAttributeString];
            image=nil;
            imageTextAttachment=nil;
            imageAttributeString=nil;
            rangeString=nil;
        }
    }
    
    return aAttributedString;
}

//根据rangeString获取plist中的图片
- (UIImage *)getImageWithRangeString:(NSString *)rangeString
{
    NSString *path =[[NSBundle mainBundle] pathForResource:@"normal_face.plist" ofType:nil];
    
    NSMutableArray *pictureArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
    //开始遍历
    for (NSDictionary * tempDict in pictureArray)
    {
        if ([tempDict[@"face_name"] isEqualToString:rangeString])
        {
            //获得字典中的图片名
            NSString * imageName = tempDict[@"face_name"];
            
            //根据图片名获取图片
            UIImage * image = [UIImage imageNamed:imageName];
            
            //返回图片
            return  image;
        }
    }
    return nil;
}

//获取系统文件
- (NSString *)documentFolderPath {
    
    NSString *documentsPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"chatFolder"];
    
    return documentsPath;
}   

//获取时间戳
- (NSString *)timeInterval {
    
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970]*1000;
    
    return [NSString stringWithFormat:@"%.0f",a];
}

//整数向上取整
int integerCeil(int number) {
    
    int res = number%LOAD_NUMBER;
    
    if(number==0) {
        
        return LOAD_NUMBER;
    }
    if(res>=0) {
        return (number-res)+LOAD_NUMBER;
    }
    return number;
}




@end
